#include <list>

#include "Pokemon.h"

Pokemon::Pokemon(int ID)
	:SDLSprite("PokemonSprite.png")
{
	dbTable = new DbTable("Pokemon.sqlite", "Pokemon", ID);
	currentId = ID;
	InitSpritePosition();

	name = this->GetTab()->Get("name");
	stringstream ss;
	ss << "SELECT type1, base_hp, base_def, base_speed FROM Pokemon WHERE id = '" << atoi(this->GetTab()->Get("id").c_str()) << "';";
	Database* db;
	db = new Database("Pokemon.sqlite");
	vector<string> data = db->GetLine(ss.str());
	type = atoi(data.at(0).c_str());
	maxHitpoint = atoi(data.at(1).c_str());
	defenceModifier = atoi(data.at(2).c_str());
	isDisabled = false;
	SetVisible(false);

	hitpoint = maxHitpoint;
	damageModifier = 1;

	atk1 = new Attack(" ",0,0);
	atk2 = new Attack(" ",0,0);
	atk3 = new Attack(" ",0,0);
	atk4 = new Attack(" ",0,0);
}

Pokemon::~Pokemon()
{

}

void Pokemon::InitSpritePosition()
{ 
	//int baseHp = atoi( dbTable->Get("base_hp").c_str() );
	//std::string name = dbTable->Get("name");
	//std::cout << baseHp << "For: " << name << std::endl;

	stringstream ss;
	ss << "SELECT f1x, f1y, f2x, f2y, bx, by FROM SpriteCoords WHERE id_pkmn = '" << atoi(this->GetTab()->Get("id").c_str()) << "';";
	Database* db;
	db = new Database("Pokemon.sqlite");
	vector<string> data = db->GetLine(ss.str());
	x1 = atoi(data.at(0).c_str());
	y1 = atoi(data.at(1).c_str());
	x2 = atoi(data.at(2).c_str());
	y2 = atoi(data.at(3).c_str());
	xBack = atoi(data.at(4).c_str());
	yBack = atoi(data.at(5).c_str());

	SetFrame(0, 0, x2, y2, 90, 80);
}

void Pokemon::DealDamage(Attack* _atk,Pokemon* _target)
{
	if(!isDisabled)
	{	
		// if !miss
		if(true /*_atk->GetAccuracy()*/)
		{
			std::cout << this->GetName() << " dealt " << _atk->GetPower() << " damage to " << _target->GetName() << " with " << _atk->GetName() << std::endl;
			_target->TakeDamage(_atk, _target);
			_target->StoreAttackEffect(_atk->GetEffect());
			this->StoreAttackEffect(_atk->GetSelfEffect());
		}
		else
		{
			std::cout << name << " has missed his attack on " << _target->GetName() << std::endl;
		}
	}
}

void Pokemon::TakeDamage(Attack* _atk, Pokemon* pf)
{
	this->hitpoint -= _atk->GetPower();

	if(hitpoint > maxHitpoint)
		hitpoint = maxHitpoint;

	std::cout << this->GetName() << " is now at " << this->GetHP() << " hitpoints" << std::endl;
}

void Pokemon::Tick()
{
	isDisabled = false;

	if(this->GetDebuff().GetTurnsLeft() < 1)
		return;

	if(this->GetDebuff().GetDamageOverTime() > 0)
		hitpoint -= this->GetDebuff().GetDamageOverTime();

	if(this->GetDebuff().GetDisable())
		isDisabled = true;
}

bool Pokemon::OnDeath()
{
	if(this->GetHP() < 1)
	{
		std::cout << this->GetName() << " has died" << std::endl;
		return true;
	}
	return false;
}

void Pokemon::StoreAttackEffect(AttackEffect _fx)
{
	buff = _fx;
}